/**
 * 客户端向服务端发起的心跳
 */
package cn.com.klun.netty.server;

import cn.com.klun.business.TaskListenerServerService;
import cn.com.klun.cache.QuartzConstants;
import cn.com.klun.netty.NettyMessage;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author chenmin-ds
 * 客户端向服务端发起的心跳
 */
public class NettyServerHeartBeatHandler extends ChannelInboundHandlerAdapter {
	
	private Logger logger = LoggerFactory.getLogger("NettyServerHeartBeatHandler");
	
	private TaskListenerServerService taskListenerServerService;
	
	public NettyServerHeartBeatHandler(TaskListenerServerService taskListenerServerService){
		this.taskListenerServerService = taskListenerServerService;
	}

	/**
	 * 通道激活时触发，当客户端connect成功后，服务端就会接收到这个事件，从而可以把客户端的Channel记录下来，供后面复用
	 */
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		try{
			Channel channel = ctx.channel();
			String ip = channel.remoteAddress().toString().replace("/", "");
			logger.info("接收到客户端的连接请求，请求地址：" + ip);
			NettyServerStartup.getInstance().putChannel(ip, channel);
		}catch(Exception e){
			logger.error("接收到客户端的连接请求，但处理异常",e);
		}
	}

	/**
	 * 出错是会触发，做一些错误处理
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		logger.info("exceptionCaught:{}",cause);
		ctx.close();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		try{
			Channel channel = ctx.channel();
			String ip = channel.remoteAddress().toString().replace("/", "");
			logger.info("监听到客户端的连接断开异常channelInactive，断开地址：" + ip);
			NettyMessage nettyMessage = new NettyMessage(QuartzConstants.CLIENT_JION_CUT);
			nettyMessage.setRequestKey(ip);
			taskListenerServerService.businessAdapter(nettyMessage);
			NettyServerStartup.getInstance().removeChannel(ip);
		}catch(Exception e){
			logger.error("监听到客户端的连接断开异常exceptionCaught,出错时会触发",e);
		}
	}
}
